package com.eco.fanliapp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.common.constant.NewsEnumLog;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.*;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.BigDecimalUtils;
import com.eco.fanliapp.utils.DateFormatUtils;
import com.eco.fanliapp.utils.ParamUtils;
import com.eco.fanliapp.utils.UUIDUtils;
import com.eco.fanliapp.vo.respone.ResponeUserResults;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author xiaoxx
 * @DateTime 2019年4月17日 下午4:36:22
 */
@Service
public class LoginServiceImpl implements ILoginService {
    private static final Logger log = LoggerFactory.getLogger(LoginServiceImpl.class);


    @Autowired
    private AppUserMapper appUserMapper;

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    private IAppUserService iAppUserService;
    @Autowired
    private IAppNewsLogService iAppNewsLogService;
    @Autowired
    private IAppCompanyService iAppCompanyService;
    @Autowired
    private AppUserRedRewardMapper appUserRedRewardMapper;
    @Autowired
    private IAppUserRedRewardService IAppUserRedRewardService;

    @Autowired
    private IAppUserRewardSetupService iAppUserRewardSetupService;
    @Autowired
    private ISyChannelService syChannelService;
    @Autowired
    private ISyChannelUserService syChannelUserService;

    @Autowired
    private IAppWxWithdrawalService iAppWxWithdrawalService;

    @Autowired
    private ISyUserMoneyService iSyUserMoneyService;

    @Autowired
    private RedisTemplateService redisTemplateService;

    @Override
    public ServerResponse<ResponeUserResults> getMobilePhoneCode(String PhoneNumber, String code) {
        if (StringUtils.isEmpty(PhoneNumber)) {
            return ServerResponse.createByErrorMessage("手机号不能为空");
        } else if (!ParamUtils.getreGex(PhoneNumber, "^((13[0-9])|(14[5,6,7,8,9])|(15[0,1,2,3,5,6,7,8,9])|(16[5,6])|(17[0,1,2,3,4,5,6,7,8])|(18[0,1,2,3,4,5,6,7,8,9])|(19[1,8,9]))\\d{8}$")) {
            return ServerResponse.createByErrorMessage("请填入正确的手机号");
        } else if (PhoneNumber.length() != 11) {
            return ServerResponse.createByErrorMessage("手机号应为11位数");
        } else {
            if ("18911111111".equals(PhoneNumber) && "123456".equals(code)
                    || "18258244110".equals(PhoneNumber) && "123456".equals(code)
                    || "18712360175".equals(PhoneNumber) && "123456".equals(code)
                    || "18906578753".equals(PhoneNumber) && "123456".equals(code)
                    || "13999999998".equals(PhoneNumber) && "123456".equals(code)
                    || "13999999999".equals(PhoneNumber) && "123456".equals(code)
                    || "13333333333".equals(PhoneNumber) && "123456".equals(code)
                    || "18839357210".equals(PhoneNumber) && "123456".equals(code)) {
                AppUser appUser4 = iAppUserService.selectAppUserByPhoneNumber(PhoneNumber);
                updateLastLoginTime(appUser4);
                return ServerResponse.createBySuccess("登录成功",
                        ResponeUser(appUser4));
            } else {
                AppUser appUser4 = iAppUserService.selectAppUserByPhoneNumber(PhoneNumber);//用户已经注册过
                if (appUser4 != null && appUser4.getPhoneNumber() != null) {
                    String verifyCode = (String) redisTemplate.opsForValue().get(PhoneNumber);
                    verifyCode = verifyCode == null ? "" : verifyCode;
                    if (!verifyCode.equals(code)) {
                        return ServerResponse.createByErrorMessage("验证码错误");
                    } else {
                        redisTemplate.delete(PhoneNumber);
                        log.info("用户{}手机号登录成功", PhoneNumber);
                        updateLastLoginTime(appUser4);
                        return ServerResponse.createBySuccess("登录成功",
                                ResponeUser(appUser4));
                    }
                } else {
                    String verifyCode = (String) redisTemplate.opsForValue().get(PhoneNumber);
                    verifyCode = verifyCode == null ? "" : verifyCode;
                    if (!verifyCode.equals(code)) {
                        return ServerResponse.createByErrorMessage("验证码错误");
                    } else {
                        redisTemplate.delete(PhoneNumber);
                        log.info("新手机用户{}", PhoneNumber);
                        ResponeUserResults results = new ResponeUserResults();
                        results.setUserWechatAuthorization(1);
                        return ServerResponse.createBySuccess("微信未绑定", results);
                    }
                }
            }
        }
    }

    /**
     * 微信登录
     * @param openId
     * @param userPic
     * @param userName
     * @param inviteCode
     * @param superInviteCode
     * @param platform
     * @param platformUnionId
     * @param channelInviteCode
     * @return
     */
    @Override
    public ServerResponse<ResponeUserResults> getUserInfo(String openId, String userPic, String userName,
                                                          String inviteCode, String superInviteCode, String platform, String platformUnionId, String channelInviteCode) {
        // TODO Auto-generated method getUserInfo
        if(channelInviteCode == null || "".equals(channelInviteCode)){
            channelInviteCode = "wR9a3L";//默认渠道
        }
        log.info("微信登录inviteCode=" + inviteCode + "channelInviteCode=" + channelInviteCode + "superInviteCode=" + superInviteCode + "userName=" + userName + "openId=" + openId);
        if (!StringUtils.isEmpty(openId)) {
            AppUser user = iAppUserService.selectAppUserByWechatUnionid(openId);

            if (user != null && user.getUserId() != null) {
                //不是第二次登陆为0 false
                user.setLoginOne(0);
                //设备信息
                user.setPlatform(platform);
                user.setPlatformUnionId(platformUnionId);
                if (userPic != null && userName != null) {
                    if (!userPic.equals(user.getUserImgUrl()) || !userName.equals(user.getUserName())) {
                        user.setUserName(userName);
                        user.setUserImgUrl(userPic);
                    }
                }

                //判断用户是否通过用户邀请授权并首次登录APP
                changeAppLogin(user);

//                user = iAppUserService.selectAppUserByWechatUnionid(openId);
                SyChannelUser syChannelUser = syChannelUserService.findSyChannelUserById(user.getUserId(), 1);
                if (syChannelUser != null) {
                    user.setChannelUserId(syChannelUser.getChannelId().toString());
                }
                if (StringUtils.isEmpty(user.getPhoneNumber())) {
                    user.setLoginOne(0);//0非首次登陆，首次登录进入任务界面时，注释掉
                    return ServerResponse.createBySuccess("登录成功",ResponeUser_1(user, "1"));//未绑定手机号
                } else {
                    user.setLoginOne(0);//0非首次登陆，首次登录进入任务界面时，注释掉
                    return ServerResponse.createBySuccess("登录成功",ResponeUser_1(user, "2"));//已绑定手机号
                }

            } else {
                Integer companyId = 1;
                if (!StringUtils.isEmpty(inviteCode)) {
                    AppUser appUser = appUserMapper.selectSuperUserInfoBySuperInviteCode(inviteCode);
                    if (appUser != null) {
                        companyId = appUser.getCompanyId();
                        //判断上级是否是渠道下的人
                        SyChannel syChannel = syChannelService.findSyChannelByUserId(appUser.getUserId());
                        if(syChannel != null){
                            channelInviteCode = syChannel.getChannelInviteCode();
                        }
                    }
                }
                if (!StringUtils.isEmpty(channelInviteCode)) {
                    SyChannel syChannel = syChannelService.findSyChannelUserById(channelInviteCode, 1);
                    if (syChannel != null) {
                        companyId = syChannel.getCompanyId();
                    }
                }
                AppUser appUser = new AppUser();
                appUser.setWechatUnionid(openId);
                appUser.setWechatNickname(userName);
                appUser.setUserName(userName);
                appUser.setUserImgUrl(userPic);
                appUser.setMeInviteCode(UUIDUtils.generateShortUuid());
                appUser.setUserLoginTime(new Date());
                appUser.setSuperInviteCode(inviteCode == null ? null : inviteCode);//上级邀请码
                appUser.setUserWechatAuthorization(2);//微信已授权
                appUser.setUserTaobaoAuthorization(1);//淘宝未授权
                appUser.setLoginOne(1);//是否第一次登陆
                appUser.setCompanyId(companyId);
                appUser.setAppLogin(0);
                appUser.setPlatform(platform);
                appUser.setPlatformUnionId(platformUnionId);
                appUser.setUserLastLoginTime(System.currentTimeMillis());//用户最后登录时间
                int i = iAppUserService.insertAppUser(appUser);
                //渠道邀请码不为空插入渠道用户表
                if (!StringUtils.isEmpty(channelInviteCode)) {
                    SyChannel syChannel = syChannelService.findSyChannelUserById(channelInviteCode, 1);
                    if (syChannel != null) {
                        SyChannelUser syChannelUser = new SyChannelUser();
                        syChannelUser.setUserId(appUser.getUserId());
                        syChannelUser.setChannelId(syChannel.getTableId());
                        syChannelUser.setChannelName(syChannel.getChannelName());
                        syChannelUser.setChannelInviteCode(channelInviteCode);
                        syChannelUser.setChannelUserStatus(2);
                        syChannelUser.setCreateTime(new Date());
                        syChannelUserService.save(syChannelUser);
                    }
                }
                if (i > 0) {
                    log.info("新微信用户{}入库成功", i);
                    AppUser user2 = iAppUserService.selectAppUserByWechatUnionid(openId);
                    int km = iSyUserMoneyService.createUserMoney(user2.getUserId());
                    if (km > 0) {
                        log.info("新人创建userMoney成功,用户{}", user2.getUserId());
                    } else {
                        log.info("新人创建userMoney失败,用户{}", user2.getUserId());
                    }
                    //微信授权登录的要记录一下消息
                    iAppNewsLogService.newsType(user2.getUserId(),
                            NewsEnumLog.NEWS_WEIXIN.getNewsType(),
                            BigDecimalUtils.Format(NewsEnumLog.NEWS_WEIXIN.getNewsMoeny()));

                    AppUserRewardSetup rewardSetup = null;
                    if (redisTemplateService.hasKey("AppUserRewardSetup")) {
                        rewardSetup = redisTemplateService.getTByKey("AppUserRewardSetup",AppUserRewardSetup.class);
                    } else {
                        rewardSetup = iAppUserRewardSetupService.getById(1);
                        redisTemplateService.set("AppUserRewardSetup", rewardSetup, 60*60);
                    }
                    Date date = new Date();
                    long time = date.getTime();
                    String createUserReward = "UserReward_"+user2.getUserId();
                    if(!redisTemplateService.hasKey(createUserReward)){
                        redisTemplateService.set(createUserReward,"创建中",60*5);
                        if (rewardSetup.getNewRedMoneyStatus() == 1) {
                            //新人红包奖励
                            //创建新人红包
                            AppUserRedReward appUserRedReward = new AppUserRedReward();
                            appUserRedReward.setUserId(user2.getUserId());
                            appUserRedReward.setHbTitle(rewardSetup.getNewRedMoneyDesc());
                            appUserRedReward.setHbMoney(rewardSetup.getNewRedMoneyFixation());
                            appUserRedReward.setHbType(1);
                            appUserRedReward.setHbStatus(1);
                            appUserRedReward.setCreateTime(time);
                            appUserRedReward.setUpdateTime(time);
                            long redInvalidTime = DateFormatUtils.addDate(date, rewardSetup.getNewRedMoneyInvalidTime()).getTime();
                            long redExpireTime = DateFormatUtils.addDate(date, rewardSetup.getNewRedMoneyExpireTime()).getTime();
                            appUserRedReward.setInvalidTime(redInvalidTime);
                            appUserRedReward.setExpireTime(redExpireTime);
                            int i1 = appUserRedRewardMapper.insertSelective(appUserRedReward);
                            log.info("新人红包记录是否成功{}用户{}", i1, user2.getUserId());
                        }

                        if (rewardSetup.getTaskRedMoneyStatus() == 1) {
                            long expireTime = DateFormatUtils.addDate(date, rewardSetup.getTaskRedMoneyExpireTime()).getTime();
                            long invalidTime = DateFormatUtils.addDate(date, rewardSetup.getTaskRedMoneyInvalidTime()).getTime();
                            AppUserRedReward appUserRedReward_newOrder = new AppUserRedReward(invalidTime, null, user2.getUserId(), rewardSetup.getTaskRedMoneyDesc(), rewardSetup.getTaskRedMoneyAmount(), 3, 1, time, expireTime, time);
                            int i2 = IAppUserRedRewardService.add(appUserRedReward_newOrder);
                            log.info("新人首单添加红包记录是否成功{}用户{}", i2, user2.getUserId());
                        }
                    }

//                    updateLastLoginTime(user2);
                    if (StringUtils.isEmpty(user2.getPhoneNumber())) {
                        user2.setSuperMember("超级会员");
                        user2.setLoginOne(0);//1首次登陆  0非首次登陆
                        return ServerResponse.createBySuccess("登录成功",
                                ResponeUser_1(user2, "1"));
                    } else {
                        user2.setSuperMember("超级会员");
                        user2.setLoginOne(0);//1首次登陆  0非首次登陆
                        return ServerResponse.createBySuccess("登录成功",
                                ResponeUser_1(user2, "2"));
                    }

                } else {
                    log.info("新微信用户{}入库失败", i);
                    return ServerResponse.createByErrorCodeMessage(500, "服务器错误");
                }
            }
        } else {
            return ServerResponse.createBySuccessMessage("请传入微信Unionid");
        }
    }

    /**
     * 用户授权后刷新用户信息状态
     * @param userId
     * @return
     */
    @Override
    public ServerResponse<ResponeUserResults> RefreshUserInfo(Long userId) {
        // TODO Auto-generated method RefreshUserInfo
        AppUser user = iAppUserService.selectAppUserByUserId(userId, 0);
        if (user != null) {
            SyChannelUser syChannelUser = syChannelUserService.findSyChannelUserById(userId, 1);
            if (syChannelUser != null) {
                user.setChannelUserId(syChannelUser.getChannelId().toString());
            }
            user.setSuperMember("超级会员");
        }

        return ServerResponse.createBySuccess("登录成功",
                ResponeUser(user));
    }
    //微信登陆后绑定手机号
    @Override
    public ServerResponse<ResponeUserResults> getBoundPhone(String phoneNumber, String unionId, String code) {
        AppUser user;
        AppUser appuser = appUserMapper.selectAppUserByPhoneNumber(phoneNumber);

        if (StringUtils.isEmpty(phoneNumber)) {
            return ServerResponse.createByErrorMessage("手机号不能为空");
        } else if (!ParamUtils.getreGex(phoneNumber, "^((13[0-9])|(14[5,6,7,8,9])|(15[0,1,2,3,5,6,7,8,9])|(16[5,6])|(17[0,1,2,3,4,5,6,7,8])|(18[0,1,2,3,4,5,6,7,8,9])|(19[1,8,9]))\\d{8}$")) {
            return ServerResponse.createByErrorMessage("请填入正确的手机号");
        } else if (phoneNumber.length() != 11) {
            return ServerResponse.createByErrorMessage("手机号应为11位数");
        } else if (appuser != null) {
            return ServerResponse.createByErrorMessage("该手机已绑定微信号");
        } else {
            if ("18911111111".equals(phoneNumber) && "123456".equals(code)
                    || "18258244110".equals(phoneNumber) && "123456".equals(code)
                    || "18712360175".equals(phoneNumber) && "123456".equals(code)
                    || "18317894323".equals(phoneNumber) && "123456".equals(code)
                    || "18906578753".equals(phoneNumber) && "123456".equals(code)
                    || "13999999998".equals(phoneNumber) && "123456".equals(code)) {

                int i = appUserMapper.updateAppUserphone(phoneNumber, unionId);
                user = iAppUserService.selectAppUserByWechatUnionid(unionId);

                if (i > 0) {

                    return ServerResponse.createBySuccess("手机号绑定成功", ResponeUser(user));
                } else {
                    return ServerResponse.createBySuccess("手机号绑定失败", ResponeUser(user));
                }

            } else {
                String verifyCode = (String) redisTemplate.opsForValue().get(phoneNumber);
                verifyCode = verifyCode == null ? "" : verifyCode;
                if (!verifyCode.equals(code)) {
                    return ServerResponse.createByErrorMessage("验证码错误");
                } else {
                    int i = appUserMapper.updateAppUserphone(phoneNumber, unionId);
                    user = iAppUserService.selectAppUserByWechatUnionid(unionId);

                    if (i > 0) {
                        return ServerResponse.createBySuccess("手机号绑定成功", ResponeUser(user));
                    } else {
                        return ServerResponse.createBySuccess("手机号绑定失败", ResponeUser(user));
                    }
                }
            }


        }


    }


    //手机号登录后进行微信登录
    @Override
    public ServerResponse<ResponeUserResults> getWXAndPhone(String phoneNumber,
                                                            String unionId, String userPic, String userName) {
        // TODO Auto-generated method getWXAndPhone
        if (phoneNumber != null && !"".equals(phoneNumber)) {//查询手机号是否已存在，存在就返回用户数据
            AppUser user5 = iAppUserService.selectAppUserByPhoneNumber(phoneNumber);
            if (user5 != null && user5.getUserWechatAuthorization() == 2) {//用户登录过并且手机和为虚拟都已绑定
                updateLastLoginTime(user5);
                changeAppLogin(user5);
                return ServerResponse.createBySuccess("登录成功",
                        ResponeUser(user5));
            } else {//手机号登录未绑定微信情况
                if (unionId != null && !"".equals(unionId)) {
                    AppUser user = iAppUserService.selectAppUserByWechatUnionid(unionId);
                    if (user != null && user.getUserWechatAuthorization() == 2) {//用户使用微信登录过
                        if (user.getPhoneNumber() == null
                                || "".equals(user.getPhoneNumber())) {//用户的手机号是空-做合并
                            AppUser userapp = new AppUser();
                            userapp.setPhoneNumber(phoneNumber);
//							 userapp.setAlipayPhoneNumber(phoneNumber);
                            userapp.setTableId(user.getTableId());
                            int i = iAppUserService.updateAppUser(userapp);
                            //判断用户是否通过邀请授权并首次登录APP
                            changeAppLogin(user);
                            if (i > 0) {
                                AppUser user4 = iAppUserService.selectAppUserByWechatUnionid(unionId);
                                updateLastLoginTime(user4);

                                return ServerResponse.createBySuccess("登录成功",
                                        ResponeUser(user4));
                            }
                        } else if (user.getPhoneNumber().equals(phoneNumber)) {//判断用户手机号是否一致
                            AppUser user4 = iAppUserService.selectAppUserByWechatUnionid(unionId);
                            updateLastLoginTime(user4);
                            return ServerResponse.createBySuccess("登录成功",
                                    ResponeUser(user4));
                        } else {//用户的手机号不一致
                            return ServerResponse.createBySuccessCodeMessage(204, "微信已绑定手机号");
                        }
                    } else {//用户没有使用微信登录过-新用户
                        AppCompany company = iAppCompanyService.findCompanyAll();//查询用户所属公司
                        AppUser user3 = new AppUser();
//					 user3.setAlipayPhoneNumber(phoneNumber);
                        user3.setPhoneNumber(phoneNumber);
                        user3.setWechatUnionid(unionId);
                        user3.setWechatNickname(userName);
                        user3.setUserName(userName);
                        user3.setUserImgUrl(userPic);
                        user3.setMeInviteCode(UUIDUtils.generateShortUuid());
                        user3.setUserWechatAuthorization(2);//微信已授权
                        user3.setUserTaobaoAuthorization(1);//淘宝未授权
                        user3.setUserCreateTime(System.currentTimeMillis());
                        user3.setUserUpdateTime(System.currentTimeMillis());
                        user3.setUserLastLoginTime(System.currentTimeMillis());
                        user3.setCompanyId(company.getCompanyId());//公司ID
                        user3.setInviteCode(company.getInviteCode());//联盟邀请码
                        int i2 = iAppUserService.insertAppUser(user3);
                        if (i2 > 0) {
                            AppUser user2 = iAppUserService.selectAppUserByWechatUnionid(unionId);
                            iAppNewsLogService.newsType(user2.getUserId(),
                                    NewsEnumLog.NEWS_WEIXIN.getNewsType(),
                                    BigDecimalUtils.Format(NewsEnumLog.NEWS_WEIXIN.getNewsMoeny()));//微信授权
                            updateLastLoginTime(user2);
                            return ServerResponse.createBySuccess("登录成功",
                                    ResponeUser(user2));
                        }
                    }
                } else {
                    return ServerResponse.createByErrorMessage("登录失败");
                }
                return ServerResponse.createByErrorMessage("登录失败");
            }
        } else {
            return ServerResponse.createByErrorMessage("手机号错误");
        }
    }

    /**
     * 手机号登录开关
     *
     * @param tableId
     * @return
     */
    @Override
    public LoginSwitch selectLoginSwitch(int tableId) {
        return appUserMapper.selectLoginSwitch(tableId);
    }


    /**
     * 封转方法
     * 统一返回数据
     *
     * @param user
     * @return
     */
    private ResponeUserResults ResponeUser(AppUser user) {
        ResponeUserResults results = new ResponeUserResults();
        results.setUserId(user.getUserId());
        results.setUserImgUrl(user.getUserImgUrl());
        results.setUserName(user.getUserName());
        results.setUserTaobaoAuthorization(user.getUserTaobaoAuthorization());
        results.setUserWechatAuthorization(user.getUserWechatAuthorization());
        results.setWechatUnionid(user.getWechatUnionid());
        results.setPhoneNumber(user.getPhoneNumber());
        results.setTaobaoUserId(user.getTaobaoUserId());
        results.setRelationId(user.getRelationId());
        results.setSpecialId(user.getSpecialId());
        results.setInviteCode(user.getInviteCode());
        results.setMeInviteCode(user.getMeInviteCode());
        results.setSuperInviteCode(user.getSuperInviteCode());
        results.setAlipayAccount(user.getAlipayAccount());
        results.setAlipayPhoneNumber(user.getAlipayPhoneNumber());
        results.setUserRealName(user.getUserRealName());
        results.setCompanyId(user.getCompanyId());
        results.setSuperMember(user.getSuperMember());
        results.setLoginOne(user.getLoginOne());
        results.setRelationName(user.getRelationName());
        results.setChannelUserId(user.getChannelUserId());
        return results;
    }

    /**
     * 封转方法
     * 统一返回数据
     *
     * @param user
     * @return
     */
    private ResponeUserResults ResponeUser_1(AppUser user, String phone_state) {
        ResponeUserResults results = new ResponeUserResults();
        results.setUserId(user.getUserId());
        results.setUserImgUrl(user.getUserImgUrl());
        results.setUserName(user.getUserName());
        results.setUserTaobaoAuthorization(user.getUserTaobaoAuthorization());
        results.setUserWechatAuthorization(user.getUserWechatAuthorization());
        results.setWechatUnionid(user.getWechatUnionid());
        results.setPhoneNumber(user.getPhoneNumber());
        results.setTaobaoUserId(user.getTaobaoUserId());
        results.setRelationId(user.getRelationId());
        results.setRelationName(user.getRelationName());
        results.setSpecialId(user.getSpecialId());
        results.setInviteCode(user.getInviteCode());
        results.setMeInviteCode(user.getMeInviteCode());
        results.setSuperInviteCode(user.getSuperInviteCode());
        results.setAlipayAccount(user.getAlipayAccount());
        results.setAlipayPhoneNumber(user.getAlipayPhoneNumber());
        results.setUserRealName(user.getUserRealName());
        results.setCompanyId(user.getCompanyId());
        results.setPhone_state(phone_state);
        results.setSuperMember(user.getSuperMember());
        results.setLoginOne(user.getLoginOne());
        results.setChannelUserId(user.getChannelUserId());
        return results;
    }

    /**
     * 封转方法
     * 统一返回数据
     *
     * @param
     * @return
     */
    private ResponeUserResults ResponeUser_2(String phone_state) {
        ResponeUserResults results = new ResponeUserResults();
        results.setPhone_state(phone_state);
        return results;
    }


    /**
     * 修改用户最后登录时间
     *
     * @param user
     */
    private void updateLastLoginTime(AppUser user) {
        AppUser appUser = new AppUser();
        appUser.setTableId(user.getTableId());
        appUser.setUserName(user.getUserName());
        appUser.setUserImgUrl(user.getUserImgUrl());
        appUser.setLoginOne(user.getLoginOne());
        appUser.setPlatform(user.getPlatform());
        appUser.setPlatformUnionId(user.getPlatformUnionId());
        appUser.setUserLastLoginTime(System.currentTimeMillis());//用户最后登录时间
        iAppUserService.updateAppUser(appUser);
    }

    /**
     * 更新用户信息
     *
     * @param userPic
     * @param userName
     * @param tableId
     */
    private void updateUserInfo(String userPic, String userName, Long tableId) {
        // TODO Auto-generated method updateUserInfo
        AppUser user = new AppUser();
        user.setUserName(userName);
        user.setWechatNickname(userName);
        user.setUserImgUrl(userPic);
        user.setTableId(tableId);
        iAppUserService.updateAppUser(user);
    }

    /**
     * 判断用户是否首次登录APP
     *
     * @param user
     */
    public void changeAppLogin(AppUser user) {

        //判断用户是否首次登录APP
        if (user.getAppLogin() == null || user.getAppLogin() != 1) {
            return;
        }
        AppUserRewardSetup rewardSetup = null;
        if (redisTemplateService.hasKey("AppUserRewardSetup")) {
            rewardSetup = redisTemplateService.getTByKey("AppUserRewardSetup",AppUserRewardSetup.class);
        } else {
            rewardSetup = iAppUserRewardSetupService.getById(1);
            redisTemplateService.set("AppUserRewardSetup", rewardSetup, 60*60);
        }

        //判断上级是否是渠道下的人//只有下级没有渠道的情况下才走这里
        SyChannel syChannel = syChannelService.findSyChannelUserById(user.getUserId().toString(), 1);

        //新人红包是否存在
        QueryWrapper<AppUserRedReward> queryWrapper = new QueryWrapper<AppUserRedReward>();
        queryWrapper.eq("user_id", user.getUserId()).eq("hb_type", 1);
        List<AppUserRedReward> list = IAppUserRedRewardService.list(queryWrapper);

        QueryWrapper<AppUserRedReward> taskQueryWrapper = new QueryWrapper<AppUserRedReward>();
        taskQueryWrapper.eq("user_id", user.getUserId()).eq("hb_type", 3);
        List<AppUserRedReward> taskList = IAppUserRedRewardService.list(taskQueryWrapper);

        try {
            dealUserInfo(user, syChannel, rewardSetup, list, taskList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Transactional
    public void dealUserInfo(AppUser user,SyChannel syChannel,AppUserRewardSetup rewardSetup,List<AppUserRedReward> list,List<AppUserRedReward> taskList) throws Exception{
        if (user.getSuperInviteCode() != null && !"".equals(user.getSuperInviteCode()) && syChannel == null) {
            //判断该用户是否存在上级
            AppUser superUser = iAppUserService.selectSuperUserInfoBySuperInviteCode(user.getSuperInviteCode());
            if (superUser != null) {
                //判断上级是否是渠道下的人
                SyChannel parentSyChannel = syChannelService.findSyChannelUserById(superUser.getUserId().toString(), 1);
                if (parentSyChannel != null) {
                    SyChannelUser syChannelUser = new SyChannelUser();
                    syChannelUser.setUserId(user.getUserId());
                    syChannelUser.setChannelId(parentSyChannel.getTableId());
                    syChannelUser.setChannelName(parentSyChannel.getChannelName());
                    syChannelUser.setChannelInviteCode(parentSyChannel.getChannelInviteCode());
                    syChannelUser.setChannelUserStatus(2);
                    syChannelUser.setCreateTime(new Date());
                    syChannelUserService.save(syChannelUser);
                }
                //消息入库 日志记录
                iAppNewsLogService.newsType(superUser.getUserId(), NewsEnumLog.NEWS_FS.getNewsType(), new BigDecimal(0), "\"" + user.getUserName() + "\"");
                // TODO: 邀请好友成功公众号提醒
                this.weCheatMessage(user, "3005", "");
            }
        }

        user.setAppLogin(0);
        user.setLoginOne(0); //非首次登陆，首次登录进入任务界面时，修改为1
        user.setUserLoginTime(new Date());
        //用户首次登陆，更新注册状态
        Integer i = iAppUserService.updateAppLogin(user);

        //新人创建userMoney
        iSyUserMoneyService.createUserMoney(user.getUserId());

        if (i > 0) {
            String createUserReward = "UserReward_"+user.getUserId();
            if(!redisTemplateService.hasKey(createUserReward)) {
                redisTemplateService.set(createUserReward, "创建中", 60 * 5);
                Date date = new Date();
                //新人红包奖励
                long time = date.getTime();

                if (rewardSetup.getNewRedMoneyStatus() == 1) {

                    if (CollectionUtils.isEmpty(list)) {
                        //创建新人红包
                        AppUserRedReward appUserRedReward = new AppUserRedReward();
                        appUserRedReward.setUserId(user.getUserId());
                        appUserRedReward.setHbTitle(rewardSetup.getNewRedMoneyDesc());
                        appUserRedReward.setHbMoney(rewardSetup.getNewRedMoneyFixation());
                        appUserRedReward.setHbType(1);
                        appUserRedReward.setHbStatus(1);
                        appUserRedReward.setCreateTime(time);
                        appUserRedReward.setUpdateTime(time);
                        long redInvalidTime = DateFormatUtils.addDate(date, rewardSetup.getNewRedMoneyInvalidTime()).getTime();
                        long redExpireTime = DateFormatUtils.addDate(date, rewardSetup.getNewRedMoneyExpireTime()).getTime();
                        appUserRedReward.setInvalidTime(redInvalidTime);
                        appUserRedReward.setExpireTime(redExpireTime);
                        int i1 = appUserRedRewardMapper.insertSelective(appUserRedReward);
                        log.info("新人红包记录是否成功{}用户{}", i1, user.getUserId());
                    }
                }

                if (rewardSetup.getTaskRedMoneyStatus() == 1) {
                    if (CollectionUtils.isEmpty(taskList)) {
                        //任务红包是否存在
                        long expireTime = DateFormatUtils.addDate(date, rewardSetup.getTaskRedMoneyExpireTime()).getTime();
                        long invalidTime = DateFormatUtils.addDate(date, rewardSetup.getTaskRedMoneyInvalidTime()).getTime();
                        AppUserRedReward appUserRedReward_newOrder = new AppUserRedReward(invalidTime, null, user.getUserId(), rewardSetup.getTaskRedMoneyDesc(), rewardSetup.getTaskRedMoneyAmount(), 3, 1, time, expireTime, time);
                        int i2 = IAppUserRedRewardService.add(appUserRedReward_newOrder);
                        log.info("新人首单添加红包记录是否成功{}用户{}", i2, user.getUserId());
                    }
                }
            }
        }

    }

    /**
     * @param appUser     用户
     * @param messageType 信息类型
     *                    30001：到账提醒模板、
     *                    30002：下单成功提醒模板，
     *                    30003：收货成功模板，
     *                    30004：好友下单成功提醒
     *                    30005：邀请好友成功
     * @param amount      金额
     */
    private void weCheatMessage(AppUser appUser, String messageType, String amount) {
        try {
            log.info("公众号发消息类型{}金额{},用户{}", messageType, amount, JSONObject.toJSONString(appUser));
            ServerResponse<String> result = iAppWxWithdrawalService.sendCashMessage(appUser, messageType, appUser.getWechatNickname(), DateFormatUtils.getCurrentDate(), amount, "微信");
            log.info("公众号发消息返回结果{}", JSONObject.toJSONString(result));
        } catch (Exception e) {
            e.printStackTrace();
            log.info("公众号发消息异常", e.getMessage());
        }
    }

    //判断当前时间是不是在30天以内
    public static Boolean is30Time(Long a) {
        //获取注册时间第N天后的时间
        if (System.currentTimeMillis() < getDateTime(a, ApiEnum.FENS_EXPIRE_TIME)) {
            return true;
        } else {
            return false;
        }
    }

    // 获取指定时间的时间戳
    private static long getDateTime(Long a, Integer start) {

        return DateUtils.addDays(new Date(a), start).getTime();
    }

    //查询用户邀请次数
    private Boolean isCount(Long userId) {
        Integer count = iAppNewsLogService.findFenSiCount(userId);
        count = count == null ? 0 : count;
        if (count <= ApiEnum.FENS_COUNT) {
            return true;
        } else {
            return false;
        }
    }

}
